package com.zw.cc.stock.util;

import com.zw.cc.stock.model.QuotesPo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * Created by zhaowuz on 2018/1/9
 */
public class HttpRequest {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequest.class);

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param){
        String urlNameString;
        if (param == null || param.length() < 1) {
            urlNameString = url;
        } else {
            urlNameString = url + "?" + param;
        }
        try {
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            return result(connection);
        } catch (IOException e) {
            LOGGER.error("",e);
        }
        return null;
    }

    private static String result(URLConnection connection) throws IOException {
        StringBuilder result;
        try(BufferedReader in = new BufferedReader(new InputStreamReader(
                connection.getInputStream(), "GBK"))) {
            result = new StringBuilder();
            // 定义 BufferedReader输入流来读取URL的响应
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        }
    }

    public static QuotesPo createBeans(String url, String param) {
        LOGGER.info(">>>>>获取实时行情 {} <<<<<<<<",param);
        String serverData = sendGet(url+param, null);
        if (!StringUtils.hasLength(serverData) || !serverData.contains("\"")) {
            return null;
        }
        QuotesPo quotes = new QuotesPo();
        serverData =  serverData.substring(serverData.indexOf('"')+1);
        String[] array = serverData.split(",");
        quotes.setName(array[0]);
        quotes.setCode(param);
        quotes.setOpening(Float.parseFloat(array[1]));
        quotes.setClose(Float.parseFloat(array[3]));
        quotes.setHighest(Float.parseFloat(array[4]));
        quotes.setLowest(Float.parseFloat(array[5]));
        quotes.setPreclose(Float.parseFloat(array[2]));
        quotes.setTradeDate(Integer.valueOf(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))));
        quotes.setTurnovervol(array[8]);
        quotes.setTurnover(array[9]);
        return quotes;
    }
}
